package com.lyl.cloud.controller;

import cn.hutool.core.util.RandomUtil;
import com.lyl.cloud.common.base.Result;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class OrderController {

    @Value("${server.port}")
    private Integer serverPort;


    @GetMapping("/hystrix/ok/{id:\\d+}")
    @HystrixCommand(fallbackMethod = "hystrix_OkHandler", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000")
    })
    public Result ok(@PathVariable("id") String id) {
        String str = serverPort + "  : ok方法调用成功，id = " + id;
        System.out.println(str);
        return Result.success(str);
    }

    public Result hystrix_OkHandler(@PathVariable("id") String id) {
        String str = "hystrix_ok  [" + Thread.currentThread().getName() + "]  参数：" + id + "  " + serverPort + " 服务器繁忙或者接口异常 ";
        log.info(str);
        return Result.success(serverPort + " 服务器繁忙或者接口异常", str);
    }

    /**
     * 如果接口超过2秒没有响应调用备选方法
     * @param id
     * @return
     */
    @GetMapping("/hystrix/timeout/{id:\\d+}")
    @HystrixCommand(fallbackMethod = "hystrix_TimeoutHandler", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
    })
    public Result timeout(@PathVariable("id") String id) {
        try {
            int timeout = RandomUtil.randomInt(4);
            TimeUnit.SECONDS.sleep(timeout);
            System.out.println(serverPort + "  : timeout进入等待，id = " + id);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String str = serverPort + "  : timeout方法调用成功，id = " + id;
        System.out.println(str);
        return Result.success(str);
    }

    /**
     * 服务降级（兜底的方法）
     *
     * @param id
     * @return
     */
    public Result hystrix_TimeoutHandler(@PathVariable("id") String id) {
        String str = "hystrix_Timeout  [" + Thread.currentThread().getName() + "]  参数：" + id + "  " + serverPort + " 服务器繁忙或者接口异常 ";
        log.info(str);
        return Result.success(serverPort + " 服务器繁忙或者接口异常", str);
    }
}
